import os, os.path, sys, wx
from wx import xrc

import matplotlib
matplotlib.use('WXAgg')
import matplotlib.pyplot as plt
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
import pylab

from subprocess import *

from DataDisplayer import DataDisplayer

class mathviewFrame(object):
    """docstring for mathviewFrame"""
    def __init__(self):
        super(mathviewFrame, self).__init__()
        self.layoutxrc = xrc.XmlResource('mathview.xrc')
        self.frame = self.layoutxrc.LoadFrame(None, 'mathview_frame')
        self.frame.SetBackgroundColour(wx.NamedColor('WHITE'))
        self.dataDisplayer = DataDisplayer(self.frame)
        self.bindEvents()
        self.initFormula()
        self.frame.Show()

    def getControl(self, xmlid):
        '''Retrieves the given control (within a frame) by its xmlid'''
        control = self.frame.FindWindowById(xrc.XRCID(xmlid))
        assert control != None, 'Programming error: a control with xml id ' + xmlid + ' was not found.'
        return control

    def bindEvents(self):
        """docstring for bindE"""
        self.frame.Bind(wx.EVT_TEXT, self.updateFormula, self.getControl('edit_textctrl'))
        self.frame.Bind(wx.EVT_BUTTON, self.saveFormulaImg, self.getControl('save_button'))
        self.frame.Bind(wx.EVT_BUTTON, self.run, self.getControl('run_button'))

    def run(self, event):
        for i in range(20):
            for i in range(30):
                    #result = Popen(cmd,shell=False,stdout=PIPE).stdout
                    cmd = 'dir'
                    #Popen(cmd,shell=False,stdout=PIPE).stdout
                    Popen(cmd,shell=True,stdout=PIPE).stdout
            self.dataDisplayer.drawGACurve(0,0)

    def complexCalculation(self):
        """docstring for complexCalculation"""
        #for i in range(100000):
            #for j in range(10):
                #2**10/2.3
                #cmd = 'dir'
        for i in range(30):
                #result = Popen(cmd,shell=False,stdout=PIPE).stdout
                cmd = 'dir'
                #Popen(cmd,shell=False,stdout=PIPE).stdout
                Popen(cmd,shell=True,stdout=PIPE).stdout

    def initFormula(self):
        """docstring for initFormula"""
        self.formulaWidth = 800
        self.formulaHeight = 100
        self.formulaString = r'$K(x_i,x_j) = x_i^T x_j$'
        self.color ='#FFFFFF'
        self.formulaImg = plt.figure()
        dpi = self.formulaImg.get_dpi()
        self.formulaImg.set_figheight(self.formulaHeight/dpi)
        self.formulaImg.set_figwidth(self.formulaWidth/dpi)

        self.formulaImg.set_facecolor(self.color)
        self.formulaImg.set_edgecolor(self.color)

        self.canvas = FigureCanvas(self.getControl('formula_panel'), -1, self.formulaImg)
        self.canvas.SetBackgroundColour(wx.NamedColor("WHITE"))
        self.getControl('formula_panel').GetSizer().Add(self.canvas, 1, wx.ALL | wx.EXPAND | wx.ALIGN_LEFT)

        self.drawFormulaImg(self.formulaString)

    def updateSize(self, event):
        """docstring for updateSize"""
        self.formulaWidth = 500
        self.formulaHeight = 50

    def updateFormula(self, event):
        """docstring for updateFormula"""
        text = event.GetEventObject().GetValue()
        formulaString = r'$'+text+'$'
        self.drawFormulaImg(formulaString)

    def drawFormulaImg(self, formulaString):
        self.formulaImg.clear()
        ax = self.formulaImg.add_subplot(111)
        ax.set_axis_bgcolor(self.color)
        for loc, spine in ax.spines.iteritems():
            spine.set_color('none')
        ax.xaxis.set_ticks([])
        ax.yaxis.set_ticks([])
        ax.text(0.1, 0.3, formulaString, {'color' : 'black', 'fontsize' : 20})
        self.canvas.draw()

    def saveFormulaImg(self):
        """docstring for save"""
        pass

class mathview(wx.App):
    """what you see is what you get mathematical formula editor"""
    def OnInit(self):
        """docstring for OnInit"""
        self.SetAppName("MathView")
        mathviewFrame()
        return True

if __name__ == '__main__':
    app = mathview(False)
    app.MainLoop()

